package gwtappcontainer.server.apis.insight;

import gwtappcontainer.server.DatastoreNamespaces;
import gwtappcontainer.server.apis.APIException;
import gwtappcontainer.shared.apis.APIResponse.Status;
import gwtappcontainer.shared.apis.insight.ProgramTypeProp;

import java.util.ArrayList;
import java.util.List;

import com.google.appengine.api.NamespaceManager;
import com.googlecode.objectify.ObjectifyService;
import static com.googlecode.objectify.ObjectifyService.ofy;


class ProgramTypeRepository {
	static {		
		ObjectifyService.factory().register(ProgramTypeEntity.class);		
	}	
	
	private final String NAMESPACE = DatastoreNamespaces.INSIGHT;
	
	List<ProgramTypeProp> list() {
		NamespaceManager.set(NAMESPACE);
		
		List<ProgramTypeEntity> entities = ofy().load().type(ProgramTypeEntity.class).list();
		
		List<ProgramTypeProp> props = new ArrayList<ProgramTypeProp>();
		
		for (ProgramTypeEntity entity : entities) {
			props.add(entity.toProp());
		}
		
		return props;
	}
	
	ProgramTypeProp add(String name) {
		NamespaceManager.set(NAMESPACE);
		List<ProgramTypeProp> all = list();
		
		//throw exception if already found
		for (ProgramTypeProp prop : all) {
			if (prop.name.equalsIgnoreCase(name))
				throw new APIException(Status.ERROR_RESOURCE_ALREADY_EXISTS, 
						"Program type [" + name + "] already exists with id [" + prop.id + "]");
		}
		
		ProgramTypeEntity entity = new ProgramTypeEntity();
		entity.name = name;
		ofy().save().entity(entity).now();
		
		return entity.toProp();		
	}
	
	ProgramTypeProp update(String newName, String existingName) {
							
		NamespaceManager.set(NAMESPACE);
		List<ProgramTypeEntity> all = ofy().load().type(ProgramTypeEntity.class).list();
		
		//throw exception if existing name does not already exist
		ProgramTypeEntity entity = null;
		for (ProgramTypeEntity e : all) {
			if (e.name.equalsIgnoreCase(existingName))
				entity = e;
		}
		
		if (entity == null)
			throw new APIException(Status.ERROR_RESOURCE_DOES_NOT_EXIST, 
					"No program type found with name [" + existingName + "]");
		
		entity.name = newName;
		ofy().save().entity(entity).now();
		
		return entity.toProp();
	}
}
